package server.jdbcdao;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import server.core.Group;
import server.core.Right;
import server.dao.GroupRightDAO;
import server.idatasource.DataSourceFactory;
import server.idatasource.IGroupRightDataSource;

public class GroupRightJdbcDAO implements GroupRightDAO {

	/*Returns all rights of the given group in a list. If an error occurs, in the first elements username field 
	 * is returned "ERROR".*/
	@Override
	public List<Right> getAllRightsByGroup(Group group) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IGroupRightDataSource groupRightData = ds.getGroupDataRightSource();

		List<List<String>> result = groupRightData.getAllRightsByGroup(group.getId());
		Iterator<List<String>> it1 = result.iterator();
		Right right;
		List<Right> rightList = new ArrayList<Right>();

		while (it1.hasNext()) {
			Iterator<String> it2 = it1.next().iterator();
			right = new Right();
			right.setId(Integer.parseInt(it2.next()));
			right.setName(it2.next());
			rightList.add(right);
		}
		return rightList;
	}

	/*Inserts a new user given in the argument, into the database. Returns a string, with the
	 * value "OK" if the operation was successful, else returns "ERROR".*/
	@Override
	public String insertGroupRight(Group group, Right right) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IGroupRightDataSource groupRightData = ds.getGroupDataRightSource();

		return groupRightData.insertGroupRight(group.getId(), right.getId());
	}

	@Override
	/*Deletes a groupRight from database, having the groupID and rightID given as argument. Returns a string, with the
	 * value "OK" if the operation was successful, else returns "ERROR".*/
	public String deleteGroupRight(Group group, Right right) {
		DataSourceFactory ds = DataSourceFactory.getInstance();
		IGroupRightDataSource groupRightData = ds.getGroupDataRightSource();

		return groupRightData.insertGroupRight(group.getId(), right.getId());
	}

}
